package com.cloud.flowable.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.flowable.entity.bo.ProcessPage;
import com.cloud.flowable.entity.WfCopy;
import com.cloud.entity.vo.TaskParam;
import com.cloud.flowable.mapper.WfCopyMapper;
import com.cloud.flowable.service.IWfCopyService;
import com.cloud.utils.SecurityUtils;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.HistoryService;
import org.flowable.engine.history.HistoricProcessInstance;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 流程抄送Service业务层处理
 */
@Service
public class WfCopyServiceImpl extends ServiceImpl<WfCopyMapper, WfCopy> implements IWfCopyService {

    @Resource
    private WfCopyMapper wfCopyMapper;

    @Resource
    private HistoryService historyService;

    /**
     * 查询流程抄送列表
     */
    @Override
    public List<WfCopy> selectList(ProcessPage procPage) {
        return wfCopyMapper.getTaskCopyList(procPage);
    }

    @Override
    public Boolean makeCopy(TaskParam taskParam) {
        if (StringUtils.isBlank(taskParam.getCopyUserIds())) {
            // 若抄送用户为空,则不需要处理,返回成功
            return true;
        }
        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
                .processInstanceId(taskParam.getProcInsId()).singleResult();
        String[] ids = taskParam.getCopyUserIds().split(",");
        List<WfCopy> copyList = new ArrayList<>(ids.length);
        Long originatorId = SecurityUtils.getUserId();
        String originatorName = SecurityUtils.getUserName();
        String title = historicProcessInstance.getProcessDefinitionName() + "-" + taskParam.getTaskName();
        for (String id : ids) {
            WfCopy copy = new WfCopy();
            copy.setCopyId(IdUtil.randomUUID());
            copy.setTitle(title);
            copy.setProcessId(historicProcessInstance.getProcessDefinitionId());
            copy.setProcessName(historicProcessInstance.getProcessDefinitionName());
            copy.setDeploymentId(historicProcessInstance.getDeploymentId());
            copy.setInstanceId(taskParam.getProcInsId());
            copy.setTaskId(taskParam.getTaskId());
            copy.setUserId(Long.valueOf(id));
            copy.setOriginatorId(originatorId);
            copy.setOriginatorName(originatorName);
            copyList.add(copy);
        }
        return this.saveBatch(copyList);
    }

}
